package models

import (
	"context"
	"errors"
	"fmt"
	"github.com/olivere/elastic/v7"
	"server/global"
	"strconv"
)

var EsClient = global.EsClient

func EsAdd(index string, data Goods) error {
	_, err := EsClient.Index().Index(index).Id(strconv.Itoa(int(data.ID))).BodyJson(data).Do(context.Background())
	if err != nil {
		return err
	}
	return nil
}

// todo: 查询
func EsHigh(index string, High *elastic.Highlight, word elastic.Query, page, size int) (*elastic.SearchResult, error) {
	data, err := EsClient.Search(index).
		Query(word).Highlight(High).
		From((page - 1) * size).
		Size(size).
		Do(context.Background())
	if err != nil {
		return nil, err
	}
	return data, nil
}

// todo: es分词索引
func EsIkIndex(index string) error {
	_, err := EsClient.CreateIndex(index).BodyString(
		`{
		"settings": {
		"analysis": {
			"analyzer": {
				"my_analyzer": {
					"tokenizer": "ik_max_word"
				}
			}
		}
	},
		"mappings": {
		"properties": {
			"title": {
				"type": "text",
					"analyzer": "my_analyzer"
			}
		}
	}
	}`).Do(context.Background())
	if err != nil {
		return err
	}
	return nil
}

// todo: 10000以上
func EsSouInfo(index string, word elastic.Query) (*elastic.SearchResult, error) {
	data, err := EsClient.Search().Index(index).Query(word).Do(context.Background())
	if err != nil {
		return nil, err
	}
	return data, nil
}

// todo: 聚合函数   排序
func EsCount(index string, word elastic.Query, title string) ([]string, error) {
	data, err := EsClient.Search().
		Index(index).
		Aggregation(title+".keyword", word).
		Do(context.Background())
	if err != nil {
		return nil, err
	}
	aggResult, found := data.Aggregations.Terms(title + ".keyword")
	if !found {
		return nil, errors.New("Aggregations not found: shang")
	}
	var res []string
	for _, bucket := range aggResult.Buckets {
		res = append(res, fmt.Sprintf("%s:%d", bucket.Key.(string), bucket.DocCount))
	}
	return res, nil
}
